//
//  ZCPreparationDetailViewController.m
//  ZhiChe-Wms
//
//  Created by 高睿婕 on 2018/9/6.
//  Copyright © 2018年 Regina. All rights reserved.
//

#import "ZCPreparationDetailViewController.h"
#import "ZCAbnormalMissingTableViewCell.h"
#import "ZCTaskTotalNumTableViewCell.h"
#import "ZCPreparationModel.h"
#import "ZCAbnormalSignViewController.h"
#import "ZCVinQRCodeViewController.h"
#import "UWRQViewController.h"


static NSString *vinNoCellID = @"ZCAbnormalMissingTableViewCell";
static NSString *infoCellID = @"ZCTaskTotalNumTableViewCell";

@interface ZCPreparationDetailViewController ()<UITableViewDelegate, UITableViewDataSource, uwRQDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *handleView;
@property (nonatomic, strong) UIButton *abnormalButton;
@property (nonatomic, strong) UIButton *commitButton;
@property (nonatomic, strong) ZCPreparationModel *prepareModel;
@property (nonatomic, strong) MBProgressHUD *hud;

@end

@implementation ZCPreparationDetailViewController
#pragma mark - 懒加载
- (UITableView *)tableView {
    if (!_tableView) {
        //space(90 * 11) + 64 + space(170)
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT) style:UITableViewStyleGrouped];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            _tableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
            _tableView.scrollIndicatorInsets = _tableView.contentInset;
            _tableView.estimatedRowHeight = 0;
            _tableView.estimatedSectionFooterHeight = 0;
            _tableView.estimatedSectionHeaderHeight = 0;
        }
        [_tableView registerClass:[ZCAbnormalMissingTableViewCell class] forCellReuseIdentifier:vinNoCellID];
        [_tableView registerClass:[ZCTaskTotalNumTableViewCell class] forCellReuseIdentifier:infoCellID];
        if (Iphone5s || Iphone6_7_8) {
            _tableView.scrollEnabled = YES;
            _tableView.showsVerticalScrollIndicator = YES;
        }else {
            _tableView.scrollEnabled = NO;
            _tableView.showsVerticalScrollIndicator = NO;
        }
    }
    return _tableView;
}

- (UIView *)handleView {
    if (!_handleView) {
        _handleView = [[UIView alloc] init];
        _handleView.backgroundColor = [UIColor whiteColor];
    }
    return  _handleView;
}

- (UIButton *)abnormalButton {
    if (!_abnormalButton) {
        _abnormalButton = [[UIButton alloc] init];
        [_abnormalButton setTitle:@"异常登记" forState:UIControlStateNormal];
        [_abnormalButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_abnormalButton setBackgroundColor:ZCColor(0xff6112, 1)];
        _abnormalButton.layer.masksToBounds = YES;
        _abnormalButton.layer.cornerRadius = space(6);
        [_abnormalButton addTarget:self action:@selector(abnormalButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _abnormalButton;
}

- (UIButton *)commitButton {
    if (!_commitButton) {
        _commitButton = [[UIButton alloc] init];
        [_commitButton setTitle:@"领取任务" forState:UIControlStateNormal];
        [_commitButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_commitButton setBackgroundColor:ZCColor(0xff6112, 1)];
        _commitButton.layer.masksToBounds = YES;
        _commitButton.layer.cornerRadius = space(6);
        [_commitButton addTarget:self action:@selector(commitButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _commitButton;
}

#pragma mark - 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"备料确认";
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 30)];
    [backButton setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    [self.view addSubview:self.tableView];
    self.tableView.backgroundColor = [UIColor whiteColor];
//    [self.view addSubview:self.handleView];
    [self.handleView addSubview:self.abnormalButton];
    [self.handleView addSubview:self.commitButton];
    [self updateViewConstraints];
    self.hud = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:self.hud];
    [self loadData];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.hud hideAnimated:YES];
    self.hud.mode = MBProgressHUDModeIndeterminate;
}

#pragma mark - 网络请求
- (void)loadData {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:self.houseId forKey:@"houseId"];
    [param setObject:self.key forKey:@"key"];
    [param setObject:self.visitType forKey:@"visitType"];
    

    [self.hud showAnimated:YES];
    __weak typeof(self)weakSelf = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [ZCHttpTool postWithURL:PrepareDetail params:param success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if ([responseObject[@"code"] integerValue] == 0) {
                [weakSelf.hud hideAnimated:YES];
                weakSelf.prepareModel = [ZCPreparationModel yy_modelWithDictionary:responseObject[@"data"]];
                [weakSelf.tableView reloadData];
                weakSelf.handleView.hidden = [weakSelf.prepareModel.status integerValue] == 10 ? NO : YES;
                weakSelf.tableView.scrollEnabled = [weakSelf.prepareModel.status integerValue] == 10 ? YES : NO;
            }else {
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = responseObject[@"message"];
                [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
            }
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            weakSelf.hud.mode = MBProgressHUDModeText;
            weakSelf.hud.label.text = error.localizedDescription;
            [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
        }];
    });
}

#pragma mark - 按钮点击
- (void)backButtonClick:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)abnormalButtonClick:(UIButton *)sender {
    ZCAbnormalSignViewController *signVC = [[ZCAbnormalSignViewController alloc] init];
    signVC.releaseId = self.prepareModel.Id;
    signVC.taskType = @"50";
    signVC.visitType = @"CLICK";
    signVC.orderNoAlloc = self.prepareModel.ownerOrderNo;
    signVC.vinAlloc = self.prepareModel.lotNo1;
    signVC.vehicleAlloc = self.prepareModel.materielId;
    signVC.storageAlloc = self.prepareModel.storeHouseName;
    signVC.isCanSend = self.prepareModel.isCanSend;
    [self.navigationController pushViewController:signVC animated:YES];
}

//领取任务
- (void)commitButtonClick:(UIButton *)sender {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:self.prepareModel.storeHouseId forKey:@"houseId"];
    [param setObject:self.prepareModel.Id forKey:@"key"];
    

    [self.hud showAnimated:YES];
    __weak typeof(self)weakSelf = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [ZCHttpTool postWithURL:PrepareCommit params:param success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if ([responseObject[@"code"] integerValue] == 0) {
                [weakSelf.hud hideAnimated:YES];
                weakSelf.prepareModel = [ZCPreparationModel yy_modelWithDictionary:responseObject[@"data"]];
                [weakSelf.tableView reloadData];
                weakSelf.handleView.hidden = [weakSelf.prepareModel.status integerValue] == 10 ? NO : YES;
            }else {
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = responseObject[@"message"];
                [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
            }
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            weakSelf.hud.mode = MBProgressHUDModeText;
            weakSelf.hud.label.text = error.localizedDescription;
            [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
        }];
    });
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 12;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 2 || indexPath.row == 11) {
        ZCAbnormalMissingTableViewCell *vinCell = [tableView dequeueReusableCellWithIdentifier:vinNoCellID forIndexPath:indexPath];
        vinCell.selectionStyle = UITableViewCellSelectionStyleNone;
        vinCell.titleColor = ZCColor(0x000000, 0.87);
        if (indexPath.row == 2) {
            vinCell.title = @"车架号";
            vinCell.content = self.prepareModel.lotNo1;
            vinCell.contentColor = ZCColor(0x000000, 0.87);
        }else if (indexPath.row == 11) {
            vinCell.title = @"实车校验";
            switch ([self.prepareModel.vehicleCheckoutStatus integerValue]) {
                case 0:
                    vinCell.content = @"未校验";
                    break;
                case 1:
                    vinCell.content = @"校验通过";
                    break;
                default:
                    break;
            }
            vinCell.contentColor = ZCColor(0xff8213, 1);
        }
        return vinCell;
    }else {
        ZCTaskTotalNumTableViewCell *infoCell = [tableView dequeueReusableCellWithIdentifier:infoCellID forIndexPath:indexPath];
        infoCell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (indexPath.row == 0) {
            infoCell.title = @"通知单号";
            infoCell.content = self.prepareModel.noticeNo;
            infoCell.contentColor = ZCColor(0x000000, 0.87);
        }else if (indexPath.row == 1) {
            infoCell.title = @"订单号";
            infoCell.content = self.prepareModel.ownerOrderNo;
            infoCell.contentColor = ZCColor(0x000000, 0.87);
        }else if (indexPath.row == 3) {
            infoCell.title = @"客户";
            infoCell.content = self.prepareModel.ownerName;
            infoCell.contentColor = ZCColor(0x000000, 0.87);
        }else if (indexPath.row == 4) {
            infoCell.title = @"预计出库时间";
            infoCell.content = self.prepareModel.recvDate;
            infoCell.contentColor = ZCColor(0x000000, 0.87);
        }else if (indexPath.row == 5) {
            infoCell.title = @"发货仓库";
            infoCell.content = self.prepareModel.storeHouseName;
            infoCell.contentColor = ZCColor(0x000000, 0.87);
        }else if (indexPath.row == 6) {
            infoCell.title = @"承运商";
            infoCell.content = self.prepareModel.carrierName;
            infoCell.contentColor = ZCColor(0x000000, 0.87);
        }else if (indexPath.row == 7) {
            infoCell.title = @"车牌号";
            infoCell.content = self.prepareModel.plateNumber;
            infoCell.contentColor = ZCColor(0x000000, 0.87);
        }else if (indexPath.row == 8) {
            infoCell.title = @"所在库位";
            infoCell.content = self.prepareModel.locationNo;
            infoCell.contentColor = ZCColor(0x000000, 0.87);
        }else if (indexPath.row == 9) {
            infoCell.title = @"备车道";
            infoCell.content = self.prepareModel.shipSpace;
            infoCell.contentColor = ZCColor(0x000000, 0.87);
        }else if (indexPath.row == 10) {
            infoCell.title = @"状态";
            infoCell.content = [self.prepareModel.status integerValue] == 10 ? @"未开始" : @"已开始";
            infoCell.contentColor = ZCColor(0xff8213, 1);
        }
        return infoCell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return space(90);
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return self.handleView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return space(170);
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

#pragma mark - UITableviewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 2) {
        ZCVinQRCodeViewController *vinVC = [[ZCVinQRCodeViewController alloc] init];
        vinVC.vin = self.prepareModel.lotNo1;
        [self.navigationController pushViewController:vinVC animated:YES];
    }else if (indexPath.row == 11) {
        UWRQViewController *uwVC = [[UWRQViewController alloc] init];
        uwVC.delegate = self;
        [self.navigationController pushViewController:uwVC animated:YES];
    }
}

#pragma mark - uwViewDelegate
- (void)uwRQFinshedScan:(NSString *)result {
    NSArray *vinArray = [result componentsSeparatedByString:@","];
    NSString *scanVin = [vinArray firstObject];
    __weak typeof(self)weakSelf = self;
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:scanVin forKey:@"condition[keyVins]"];
    [param setObject:self.prepareModel.Id forKey:@"condition[lineIds]"];
    
    [weakSelf.hud showAnimated:YES];
    weakSelf.hud.mode = MBProgressHUDModeText;
    weakSelf.hud.label.text = nil;
    [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
    [ZCHttpTool postWithURL:VehicleCheck params:param success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"code"] integerValue] == 0) {
            [weakSelf.hud hideAnimated:YES];
            [weakSelf loadData];
        }else {
            weakSelf.hud.mode = MBProgressHUDModeText;
            weakSelf.hud.label.text = responseObject[@"message"];
            [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
        }
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        weakSelf.hud.mode = MBProgressHUDModeText;
        weakSelf.hud.label.text = error.localizedDescription;
        [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
    }];
    
}

#pragma mark - 布局
- (void)updateViewConstraints {
    [super updateViewConstraints];
    __weak typeof(self)weakSelf = self;
    
    [_abnormalButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(weakSelf.handleView.mas_centerY);
        make.left.equalTo(weakSelf.handleView.mas_left).offset(space(80));
        make.right.equalTo(weakSelf.handleView.mas_centerX).offset(-space(40));
        make.height.mas_equalTo(space(90));
    }];
    
    [_commitButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.handleView.mas_centerX).offset(space(40));
        make.right.equalTo(weakSelf.handleView.mas_right).offset(-space(80));
        make.centerY.equalTo(weakSelf.abnormalButton.mas_centerY);
        make.height.equalTo(weakSelf.abnormalButton.mas_height);
    }];
}

@end
